/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.deliveryticket;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.TransactionValidate;
import com.lightkits.common.db.entity.FndUomBase;
import com.lightkits.common.db.entity.SysFile;
import com.lightkits.common.db.entity.WmDeliveryTicketLine;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.json.JsonUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsDeliveryTicketLineMapper;
import com.lightkits.wms.database.dao.WmsDeliveryTicketMapper;
import com.lightkits.wms.database.model.DeliveryTicketLineModel;
import com.lightkits.wms.database.model.WmSimTicketModel;
import com.lightkits.wms.domain.usuallyinterface.GetWmMoveTypeExecutor;
import com.lightkits.wms.dto.deliveryticket.QueryTicketByIdRequestType;
import com.lightkits.wms.dto.deliveryticket.QueryTicketByIdResponseType;
import com.lightkits.wms.dto.deliveryticket.models.TicketHeadAndLineDTO;
import com.lightkits.wms.util.models.LineControl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * QueryTicketByIdExecutor
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/20 14:11
 */
@Component
public class QueryTicketByIdExecutor implements
        ServiceExecutor<QueryTicketByIdRequestType, QueryTicketByIdResponseType> {
    private final WmsDeliveryTicketLineMapper wmDeliveryTicketLineMapper;
    private final Logger logger = LoggerFactory.getLogger(GetWmMoveTypeExecutor.class);

    private final WmsDeliveryTicketMapper wmDeliveryTicketMapper;

    @Autowired
    public QueryTicketByIdExecutor(WmsDeliveryTicketLineMapper wmDeliveryTicketLineMapper,
                                   WmsDeliveryTicketMapper wmDeliveryTicketMapper) {
        this.wmDeliveryTicketLineMapper = wmDeliveryTicketLineMapper;
        this.wmDeliveryTicketMapper = wmDeliveryTicketMapper;
    }

    @Override
    public QueryTicketByIdResponseType service(QueryTicketByIdRequestType request) {
        QueryTicketByIdResponseType response = new QueryTicketByIdResponseType();
        response.setSuccessful(true);
        try {
            //非空校验
            IntegrityValidator.begin()
                    .validate(request.getTicketLineId(), "Ticket Line Id");
            //有效性校验
            TransactionValidate check1 = TransactionValidate.beginValidity(WmDeliveryTicketLine.class);
            check1.checkIdValidity(ObjectUtil.toString(request.getTicketLineId()), "ID");
            //获取送货单行
            List<DeliveryTicketLineModel> lineModels = wmDeliveryTicketLineMapper.queryTicketLineByParams(
                    "", request.getTicketLineId());
            if (ObjectUtil.isNullOrEmpty(lineModels) || lineModels.size() != 1) {
                response.setSuccessful(false);
                response.setMessage("the ticketLineId is invalid");
                return response;
            }
            TicketHeadAndLineDTO dto = convertLine(lineModels.get(0));
            if (ObjectUtil.isEmpty(dto) || ObjectUtil.isNullOrEmpty(dto.getTicketId())) {
                response.setSuccessful(false);
                response.setMessage("the ticket head meassge is missed");
                return response;
            }
            //获取送货当头
            List<WmSimTicketModel> headModels = wmDeliveryTicketMapper.queryTicketByIdOrNum(dto.getTicketId());
            if (ObjectUtil.isNullOrEmpty(headModels) || headModels.size() != 1) {
                response.setSuccessful(false);
                response.setMessage("the ticketId is invalid");
                return response;
            }
            dto = convertHead(headModels.get(0), dto);
            response.setDto(dto);
        } catch (LightKitsBizException e) {
            response.setSuccessful(false);
            String mes = StringUtils.substringAfterLast(e.getMessage(), ":");
            response.setMessage(ObjectUtil.isNullOrEmpty(mes) ? e.getMessage() : mes);
        } catch (Exception e) {
            e.printStackTrace();
            response.setSuccessful(false);
            response.setMessage("get All Ticket  Message Error");
        }
        return response;
    }

    /**
     * 转换送货单行
     *
     * @param lineModel 送货单行信息
     * @return TicketHeadAndLineDTO
     */
    private TicketHeadAndLineDTO convertLine(DeliveryTicketLineModel lineModel) {
        TicketHeadAndLineDTO dto = new TicketHeadAndLineDTO();
        try {
            dto.setTicketLineId(lineModel.getTicketLineId());
            dto.setTicketId(lineModel.getTicketId());
            dto.setItemId(lineModel.getItemId());
            dto.setItemCode(lineModel.getItemCode());
            dto.setItemDesc(lineModel.getItemDesc());
            dto.setUomName(lineModel.getUomName());
            //根据单位的类型保留小数位数
            FndUomBase uomBase = new FndUomBase().selectOne(new EntityWrapper()
                    .eq(FndUomBase.UOM_CODE, lineModel.getUomName()));
            if (ObjectUtil.isEmpty(uomBase)) {
                dto.setReceivedQty(lineModel.getReceivedQty().toString());
                dto.setInventoryQty(lineModel.getInventoryQty().toString());
            } else {
                dto.setReceivedQty(lineModel.getReceivedQty()
                        .setScale(uomBase.getDecimalNumber().intValue(),
                                BigDecimal.ROUND_HALF_UP).toString());
                dto.setInventoryQty(lineModel.getInventoryQty()
                        .setScale(uomBase.getDecimalNumber().intValue(),
                                BigDecimal.ROUND_HALF_UP).toString());
            }
            dto.setReciveWarehouseId(lineModel.getReciveWarehouseId());
            dto.setReceiveWarehouseName(lineModel.getReceiveWarehouseName());
            dto.setReciveWmAreaId(lineModel.getReciveWmAreaId());
            dto.setReceiveWmAreaName(lineModel.getReceiveWmAreaName());
            dto.setInventoryWarehouseId(lineModel.getInventoryWarehouseId());
            dto.setInventoryWarehouseName(lineModel.getInventoryWarehouseName());
            dto.setInventoryWmAreaId(lineModel.getInventoryWmAreaId());
            dto.setInventoryWmAreaName(lineModel.getInventoryWmAreaName());
            dto.setInventoryWorkerName(lineModel.getInventoryWorkerName());
            dto.setInventoryWorkerNum(lineModel.getInventoryWorkerNum());
            dto.setPartyLotCode(lineModel.getPartyLotCode());
            dto.setPoNum(lineModel.getPoNum());
            //json格式的图片ID进行转换并查询其url
            if (!ObjectUtil.isNullOrEmpty(lineModel.getLineControls())) {
                LineControl lineControl = JsonUtil.parse(lineModel.getLineControls(), LineControl.class);
                List<String> pictureIds = lineControl.getPictureIds();
                List<String> pictureUrls = new ArrayList<>();
                pictureIds.forEach(target -> {
                    SysFile sysFile = new SysFile().selectById(target);
                    if (sysFile != null) {
                        pictureUrls.add(sysFile.getFileUrl());
                    }
                });
                dto.setPictureUrls(pictureUrls);
            }
        } catch (Exception e) {
            logger.error("convertLine.error", e);
            throw new LightKitsBizException(e);
        }
        return dto;
    }

    /**
     * 转换送货单头
     *
     * @param model 送货单头信息
     * @param dto   送货单头行详情
     * @return TicketHeadAndLineDTO
     */
    private TicketHeadAndLineDTO convertHead(WmSimTicketModel model, TicketHeadAndLineDTO dto) {
        try {
            dto.setTicketNum(model.getTicketNum());
            dto.setTicketStatus(model.getTicketStatus());
            dto.setPartyId(model.getPartyId());
            dto.setPartyName(model.getPartyName());
            dto.setPartySiteId(model.getPartySiteId());
            dto.setPartySiteName(model.getPartySiteName());
            dto.setOrgId(model.getOrgId());
            dto.setOrgName(model.getOrgName());
            dto.setReceiveWorkerName(model.getWorkerName());
            dto.setReceiveWorkerNum(model.getWorkerNum());
        } catch (Exception e) {
            logger.error("convertHead.error", e);
            throw new LightKitsBizException(e);
        }
        return dto;
    }
}
